<?php

/**
 * основной контроллер сайта
 * @author yura
 */
class MainController extends Controller{
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','stat'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('vote'),
				'users'=>array('@'),
			),
//			array('allow', // allow admin user to perform 'admin' and 'delete' actions
//				'actions'=>array('admin','delete'),
//				'users'=>array('admin'),
//			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * главная страница
	 */
	public function actionIndex(){
		$criteria = new CDbCriteria;
		$criteria -> order = 'Points';
		$criteria -> limit = 5;
		
		$best = new CActiveDataProvider('Item',array(
			'criteria' => $criteria,
		));
		
		$this -> render('index',array('dataProvider' => $best));
	}
	
	/**
	 * Страница голосования
	 */
	public function actionVote(){
		if(isset($_POST['voteFor'])){
			$for     = Item::model() -> findByPk($_POST['voteFor']);
			$against = Item::model() -> findByPk($_POST['voteAgainst']);
			
			if(empty($for) || empty($against))
				throw new CHttpException(500,'Ошибка данных');
			
			$for     -> Compares = intval($for -> Compares) + 1;
			$against -> Compares = intval($against -> Compares) + 1;
			
			$for     -> Points = intval($for -> Points) + 1;
			
			$for     -> save();
			$against -> save();
			
			Yii::app() -> request -> redirect('/poiskdemo/main/vote');
		}
		
		$userId = Yii::app() -> user -> Id;		
		$items = Item::findVotePair($userId);
		
		$this -> render('vote',array(
			'items' => $items,
		));
	}
	
	/**
	 * Страница статистики
	 */
	public function actionStat(){
		$criteria = new CDbCriteria;
		
		$criteria -> order = 'Points DESC';
		
		$all = new CActiveDataProvider('Item',array(
			'criteria' => $criteria,
			'pagination' => array(
				'pageSize' => 50,
			),
		));
		
		$this -> render('stat',array('dataProvider' => $all));
	}
	
}